package com.s59.rabc.security;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

@Data
public class UserDetailsimpl implements UserDetails {
    private String username;
    private String password;
    private String nickname;
    private Set<String> roleNames = new HashSet<>();
    private Set<String> permsList = new HashSet<>();

    /**
     * 在spring security鉴权时自动调用
     * @return
     */
    @Override
    @JsonDeserialize(using = CustomAuthorityDeserializer.class)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new ArrayList<>();
//        for (String roleName : roleNames) {
//            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+roleName);
//            list.add(authority);
//        }
//        for (String permsList : permsList) {
//            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permsList);
//            list.add(authority);
//        }
        list.addAll(roleNames.stream().map(roleNames -> new SimpleGrantedAuthority("ROLE_"+roleNames)).collect(Collectors.toList()));
        list.addAll(permsList.stream().map(p -> new SimpleGrantedAuthority(p)).collect(Collectors.toList()));
        return list;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
